package com.hengxinguotong.zhihuichengjian.ui;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.PersonnelRes;
import com.hengxinguotong.zhihuichengjian.bean.AuthorType;
import com.hengxinguotong.zhihuichengjian.bean.AuthorTypeRes;
import com.hengxinguotong.zhihuichengjian.bean.Team;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.bean.WorkType;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.ServiceCompanyActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.CircleImageView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectPositionPop;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 添加跟查看人员界面   新增修改头像功能
 * Created by liux on 2017/3/1.
 */

public class AddPersonnelActivity extends BaseActivity implements View.OnClickListener,AualityTestAddPicAdapter.OnRecyclerViewClickListener{
    @BindView(R.id.main_ll)
    LinearLayout mainLl;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.add_avater_ll)
    LinearLayout addAvaterLl;
    @BindView(R.id.avater_iv)
    CircleImageView avaterIv;
    @BindView(R.id.update_head_portrait)
    HXTextView updateHeadPortrait;
    @BindView(R.id.name_ev)
    HXEditTextView nameEv;
    @BindView(R.id.switch_sex)
    Switch switch_sex;
    @BindView(R.id.sex_rl)
    RelativeLayout sexRl;
    @BindView(R.id.idcard_ev)
    HXEditTextView idcardEv;
    @BindView(R.id.mobile_ev)
    HXEditTextView mobileEv;
    @BindView(R.id.team_tv)
    HXTextView teamTv;
    @BindView(R.id.team_rl)
    RelativeLayout teamRl;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.company_rl)
    RelativeLayout companyRl;
    @BindView(R.id.position_tv)
    HXTextView positionTv;
    @BindView(R.id.position_rl)
    RelativeLayout positionRl;
    @BindView(R.id.switch_group)
    Switch switch_group;
    @BindView(R.id.card_type_rl)
    RelativeLayout cardTypeRl;
    @BindView(R.id.card_type_et)
    HXTextView cardTypeEt;
    @BindView(R.id.card_num_et)
    HXEditTextView cardNumEt;
    @BindView(R.id.card_date_rl)
    RelativeLayout cardDateRl;
    @BindView(R.id.card_date_et)
    HXTextView cardDateEt;
    @BindView(R.id.card_efect_rl)
    RelativeLayout cardEfectRl;
    @BindView(R.id.card_efect_et)
    HXTextView cardEfectEt;
    @BindView(R.id.card_department_et)
    HXEditTextView cardDepartmentEt;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;

    private Gson gson;
    private List<AuthorType> authorTypeList;
    private String cetificationType = "-1";//证书类型
    private String workTypeId = null;//工种岗位id
    public static final int AVATER = 5;
    private SelectPositionPop mSelectListPop;
    private File avaterFile;
    private String sex = "1";//1男 2女
    private String isLeader = "0";//是否是班组长（.0:不是班组长;1:是班组长）
    public static final int ADDTYPE = 1;
    public static final int MODTYPE = 2;
    private int type;
    private String personId;
    private User modUser;
    private File modAvaterFile;
    private boolean isMod = false;
    private Company company;
    private Team team;
    private List<String> paths;
    private List<String> minPaths;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addpersonnel);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", ADDTYPE);
        paths = new ArrayList<String>();
        paths.add(Utils.ADDPIC);
        if (type == MODTYPE) {
            personId = getIntent().getStringExtra("personId");
            getPersonnelInfo();
            tvTitleName.setText("人员详情");
            saveTv.setVisibility(View.GONE);
        }else{
            getCardType("");
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
            addPicRv.setLayoutManager(getLinearLayoutManager());
            addPicRv.setAdapter(aualityTestAddPicAdapter);
            Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            monthOfYear = c.get(Calendar.MONTH);
            dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
            switch_group.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        isLeader = "1";
                    }else{
                        isLeader = "0";
                    }
                }
            });
            switch_sex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        sex = "1";
                    }else{
                        sex = "2";
                    }
                }
            });
        }
    }

    private void getPersonnelInfo() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("personId", personId);
        Utils.requestData(getResources().getString(R.string.loading), this, "/person/detailInfo/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    gson = new Gson();
                    PersonnelRes personnelRes = gson.fromJson(json, PersonnelRes.class);
                    modUser = personnelRes.getValue();
                    if(personnelRes.getStatus() == 1){
                        initModView(modUser);
                    }else{
                        showToast(personnelRes.getMsg());
                    }

                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initModView(User user) {
        if (!Utils.isEmpty(user.getHeadPortrait())) {
//            String headPortrait =Utils.SERVER_PIC + user.getHeadPortrait().substring(0, user.getHeadPortrait().indexOf(".")) + "_100x100.jpg";
            Glide.with(this).load(user.getHeadPortrait()).placeholder(R.mipmap.icon_avater_defalut).dontAnimate().error(R.mipmap.icon_avater_defalut).into(avaterIv);
        }
        String userId = SPUtil.getString(this, "userId");
        if(hasEdit() || (user.getUserId() != null && user.getUserId().equals(userId))){
            updateHeadPortrait.setVisibility(View.VISIBLE);
        }
        Utils.setEditTextViewUnable(user.getName(), nameEv);
        if("男".equals(user.getSex())){
            switch_sex.setChecked(true);
        }else{
            switch_sex.setChecked(false);
        }
        switch_sex.setEnabled(false);
        Utils.setEditTextViewUnable(user.getIdCard(), idcardEv);
        Utils.setEditTextViewUnable(user.getMobile(), mobileEv);
        Utils.setEditTextViewUnable(user.getProjectCompanyName(), companyTv);
        Utils.setEditTextViewUnable(user.getTeamName(), teamTv);
        Utils.setEditTextViewUnable(user.getPositionWorktype(), positionTv);
        if("1".equals(user.getIsLeader())){
            switch_group.setChecked(true);
        }else{
            switch_group.setChecked(false);
        }
        switch_group.setEnabled(false);
        Utils.setEditTextViewUnable(user.getType(), cardTypeEt);
        Utils.setEditTextViewUnable(user.getNumber(), cardNumEt);
        Utils.setEditTextViewUnable(user.getIssueDate(), cardDateEt);
        Utils.setEditTextViewUnable(user.getValidDate(), cardEfectEt);
        Utils.setEditTextViewUnable(user.getIssueOrgans(), cardDepartmentEt);
        if (user.getPicList().size() == 0) {
            noPicTv.setVisibility(View.VISIBLE);
        } else {
            paths = user.getPicList();
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
            addPicRv.setLayoutManager(getLinearLayoutManager());
            addPicRv.setAdapter(aualityTestAddPicAdapter);
        }
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    private boolean checkInformation() {
        if (Utils.isEmpty(nameEv.getEditableText().toString())) {
            showToast("请填写名字");
            return false;
        }

        if (Utils.isEmpty(idcardEv.getEditableText().toString())) {
            showToast("请填写身份证号");
            return false;
        }

        if (Utils.isEmpty(workTypeId)) {
            showToast("请选择工种岗位");
            return false;
        }

        if (Utils.isEmpty(mobileEv.getEditableText().toString())) {
            showToast("请填写电话");
            return false;
        }

        if (company == null) {
            showToast("请选择所属公司");
            return false;
        }

        if (team == null) {
            showToast("请选择所属班组");
            return false;
        }

        return true;
    }

    private void getMinImage() {
        if(type == ADDTYPE){
            if (!checkInformation()) {
                return;
            }
        }
        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    addPersonnel();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addPersonnel();
        }
    }

    private void addPersonnel() {
        RequestParams params = new RequestParams();
        if(type == MODTYPE){
            params.addBodyParameter("id", personId);
            if (modAvaterFile != null && modAvaterFile.exists()) {
                params.addBodyParameter("headFile", modAvaterFile);
            }
        }else{
            if (!checkInformation()) {
                return;
            }

            params.addBodyParameter("name", nameEv.getEditableText().toString());
            params.addBodyParameter("sex", sex);
            params.addBodyParameter("positionWorkId", workTypeId);
            params.addBodyParameter("idCard", idcardEv.getEditableText().toString());
            params.addBodyParameter("mobile", mobileEv.getEditableText().toString());
            if (avaterFile != null && avaterFile.exists()) {
                params.addBodyParameter("headFile", avaterFile);
            }
            params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
            params.addBodyParameter("isLeader", isLeader);
            for (int i = 0; i < minPaths.size(); i++) {
                params.addBodyParameter("qualificationCertificateFile[" + i + "]", new File(minPaths.get(i)));
            }
            params.addBodyParameter("orgId", SPUtil.getString(this, "orgid"));
            params.addBodyParameter("projectCompanyId", company.getId());
            params.addBodyParameter("teamId", team.getId());
            if(!cetificationType.equals("-1")){
                params.addBodyParameter("type", cetificationType);
            }
            if(!Utils.isEmpty(cardNumEt.getEditableText().toString())){
                params.addBodyParameter("number", cardNumEt.getEditableText().toString());
            }
            if(!Utils.isEmpty(cardDateEt.getText().toString())){
                params.addBodyParameter("issueDate", cardDateEt.getText().toString());
            }
            if(!Utils.isEmpty(cardEfectEt.getText().toString())){
                params.addBodyParameter("validDate", cardEfectEt.getText().toString());
            }
            if(!Utils.isEmpty(cardDepartmentEt.getEditableText().toString())){
                params.addBodyParameter("IssueOrgans", cardDepartmentEt.getEditableText().toString());
            }
        }
        Utils.requestData("加载中 . . .", this, "/person/addPerson/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    if(status == 1) {
                        showToast("提交成功");
                        setResult(1);
                        finish();
                    }else{
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /*
     *查询证书类型
     */
    private void getCardType(String alert) {
        Utils.requestData(alert, this, "/person/queryQualification/" + SPUtil.getString(this,"uuid"), null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    gson = new Gson();
                    AuthorTypeRes authorTypeRes = gson.fromJson(json, AuthorTypeRes.class);
                    authorTypeList = authorTypeRes.getValue();
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        switch (requestCode){
            case 1:
                company = (Company) data.getSerializableExtra("company");
                companyTv.setText(company.getName());
                break;
            case 4:
                team = (Team) data.getSerializableExtra("team");
                teamTv.setText(team.getName());
                break;
            case 2:
                if(resultCode == 0){
                    WorkType workType = (WorkType) data.getSerializableExtra("workType");
                    workTypeId = workType.getId();
                    positionTv.setText(workType.getName());
                }
                break;
            case 3:
                AuthorType cetificationBean = (AuthorType) data.getSerializableExtra("type");
                cetificationType = cetificationBean.getValue();
                cardTypeEt.setText(cetificationBean.getName());
                break;
            case AVATER:
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (path == null || path.size() == 0) {
                    return;
                }
                loadFile(requestCode, path.get(0));
                saveTv.setVisibility(View.VISIBLE);
                break;
            case 9:
                paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                paths.add(Utils.ADDPIC);
                if (aualityTestAddPicAdapter != null) {
                    aualityTestAddPicAdapter.setPaths(paths);
                }
                break;
        }
    }


    private void loadFile(final int requestCode, final String path) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                String miniPath = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                FileUtil.writeByteArrayToPath(miniPath, FileUtil.handleUploadImg(path));
                switch (requestCode) {
                    case AVATER:
                        if (type == ADDTYPE) {
                            avaterFile = new File(miniPath);
                        } else {
                            modAvaterFile = new File(miniPath);

                        }
                        break;

                }
                return null;
            }


            @Override
            protected void onPostExecute(Void aVoid) {
                switch (requestCode) {
                    case AVATER:
                        if (type == ADDTYPE) {
                            Glide.with(AddPersonnelActivity.this).load(avaterFile).into(avaterIv);
                        } else {
                            Glide.with(AddPersonnelActivity.this).load(modAvaterFile).into(avaterIv);

                        }
                        break;

                }

            }

        }.execute();

    }

    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private void showWheelViewDialog(final HXTextView tv) {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        AddPersonnelActivity.this.year = year;
                        AddPersonnelActivity.this.monthOfYear = monthOfYear;
                        AddPersonnelActivity.this.dayOfMonth = dayOfMonth;
                        tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }

    @OnClick({R.id.company_rl, R.id.team_rl, R.id.save_tv, R.id.add_avater_ll, R.id.position_rl, R.id.card_type_rl, R.id.iv_back,
            R.id.card_date_rl, R.id.card_efect_rl, R.id.update_head_portrait})
    public void onClick(View view) {
        Intent intent;
        ArrayList<String> paths = null;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.company_rl:
                if (type == MODTYPE) {
                    return;
                }
                intent = new Intent(this, ServiceCompanyActivity.class);
                intent.putExtra("companyType",ServiceCompanyActivity.FROMPERSON);
                intent.putExtra("type",ServiceCompanyActivity.SERVICECOMPANY);
                startActivityForResult(intent, 1);
                break;
            case R.id.team_rl:
                if (type == MODTYPE) {
                    return;
                }
                if(company == null){
                    showToast("请先选择公司");
                    return;
                }
                intent = new Intent(this, TeamSelectListActivity.class);
                intent.putExtra("title", "选择班组");
                intent.putExtra("projectCompanyId", company.getId());
                startActivityForResult(intent, 4);
                break;
            case R.id.add_avater_ll:
                if (type == MODTYPE && modUser.getHeadPortrait() != null) {
                    paths = new ArrayList<String>();
                    paths.add(modUser.getHeadPortrait());
                    Intent imgIntent = new Intent(this, TaskBigImgActivity.class);
                    imgIntent.putStringArrayListExtra("paths",(ArrayList<String>) paths);
                    imgIntent.putExtra("title","缺陷记录图片");
                    imgIntent.putExtra("position", 0);
                    return;
                }

                MultiImageSelector.create()
                        .showCamera(true) // show camera or not. true by default_grey
                        .count(1) // max select image size, 9 by default_grey. used width #.multi()
                        .single() // single mode
                        .start(this, AVATER);
                break;
            case R.id.position_rl:
                if (type == MODTYPE) {
                    return;
                }
                intent = new Intent(this, WorktypeListActivity.class);
                intent.putExtra("title", "岗位工种");
                startActivityForResult(intent, 2);
                break;
            case R.id.card_type_rl:
                if (type == MODTYPE) {
                    return;
                }
                intent = new Intent(this, MenuActivity.class);
                intent.putExtra("title", "证书类别");
                intent.putExtra("list", (Serializable) authorTypeList);
                startActivityForResult(intent, 3);
                break;
            case R.id.save_tv:
                getMinImage();
                break;
            case R.id.card_date_rl:
                showWheelViewDialog(cardDateEt);
                break;
            case R.id.card_efect_rl:
                showWheelViewDialog(cardEfectEt);
                break;
            case R.id.update_head_portrait:
                MultiImageSelector.create()
                        .showCamera(true) // show camera or not. true by default_grey
                        .count(1) // max select image size, 9 by default_grey. used width #.multi()
                        .single() // single mode
                        .start(this, AVATER);
                break;
        }
    }

    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(5) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 9);
        } else {
            if (modUser != null) {
                Intent imgIntent = new Intent(this, TaskBigImgActivity.class);
                imgIntent.putStringArrayListExtra("paths",(ArrayList<String>) paths);
                imgIntent.putExtra("title","缺陷记录图片");
                imgIntent.putExtra("position", position);
            } else {
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }
    }

}
